﻿namespace EFS.RC.CCAdmin.Agents
{
	public partial class Edit : EFS.RC.CCAdmin.Common.Control
	{ 
		private System.Int32 officeEndpointID = 0;
		private EFS.RC.CC.Deployment.Views.Operators.AgentADDetails agentDetails;
		private EFS.Common.UI.Controls.ModalDialogHost host = null;
        public static System.Int32[] SkillValues = new System.Int32[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        private EFS.RC.CC.Deployment.Entities.Skill[] skillsCached = new EFS.RC.CC.Deployment.Entities.Skill[0];

		#region Constructors

		public Edit()
		{
			InitializeComponent();

			// ignore in desiger
			if (!System.ComponentModel.DesignerProperties.IsInDesignTool)
			{
				throw new System.Exception("Do not use this constructor at runtime!");
			}
		}

		public Edit(
			EFS.Common.UI.Controls.ModalDialogHost host,
			EFS.RC.CC.Deployment.Views.Operators.AgentADDetails agentDetails,
			System.Int32 officeEndpointID)
		{
			InitializeComponent();

			//set
			this.host = host;
			this.officeEndpointID = officeEndpointID;
			this.agentDetails = agentDetails;

			// register ok click
			host.OnButtonOKClick += SaveAgent;

			// set events
			this.Loaded += new System.Windows.RoutedEventHandler(Edit_Loaded);

			// service events
			UtilitiesService.Agent_CreateCompleted += new System.EventHandler<WebProxy.Agent_CreateCompletedEventArgs>(UtilitiesService_Agent_CreateCompleted);
			UtilitiesService.AgentAD_GetByIDCompleted += new System.EventHandler<WebProxy.AgentAD_GetByIDCompletedEventArgs>(UtilitiesService_AgentAD_GetByIDCompleted);
			UtilitiesService.Agent_UpdateCompleted += new System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(UtilitiesService_Agent_UpdateCompleted);
			UtilitiesService.Skills_GetAllCompleted += new System.EventHandler<WebProxy.Skills_GetAllCompletedEventArgs>(UtilitiesService_Skills_GetAllCompleted);
			UtilitiesService.AgentSkill_GetByAgentIDCompleted += new System.EventHandler<WebProxy.AgentSkill_GetByAgentIDCompletedEventArgs>(UtilitiesService_AgentSkill_GetByAgentIDCompleted);
		}

		#endregion

		#region Properties

		/// Property IsValid: Get
		public System.Boolean? IsValid
		{
			get
			{
				// update grid
				foreach (EFS.RC.CC.Deployment.Entities.Skill skill in this.skillsCached)
				{
					// get checkbox
					System.Windows.Controls.CheckBox chk = dataGridSkills.Columns[0].GetCellContent(skill) as System.Windows.Controls.CheckBox;

					// only if checked
					if (chk.IsChecked.HasValue && chk.IsChecked.Value)
					{
						// get combo
						System.Windows.Controls.ComboBox comboSkilled = dataGridSkills.Columns[2].GetCellContent(skill) as System.Windows.Controls.ComboBox;

						// check selection in skilled combo
						if (null == comboSkilled.SelectedValue)
						{
							return false;
						}
					}
				}

				// ok
				return true;
			}
		}

		/// Property SelectedSkills: Get, Set
		public EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill[] SelectedSkills
		{
			get
			{
				// create int list
				System.Collections.Generic.List<EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill> retValue = new System.Collections.Generic.List<EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill>();

				// update grid
				foreach (EFS.RC.CC.Deployment.Entities.Skill skill in this.skillsCached)
				{
					// get checkbox
					System.Windows.Controls.CheckBox chk = dataGridSkills.Columns[0].GetCellContent(skill) as System.Windows.Controls.CheckBox;

					// get combo
					System.Windows.Controls.ComboBox comboSkilled = dataGridSkills.Columns[2].GetCellContent(skill) as System.Windows.Controls.ComboBox;

					// get ID
					System.Int32 skillID = System.Int32.Parse(chk.CommandParameter.ToString());

					// check/or not
					if (chk.IsChecked.HasValue && chk.IsChecked.Value && null != comboSkilled.SelectedValue)
					{
						EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill agentSkill = new EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill();
						agentSkill.AgentID = null == agentDetails? null: agentDetails.ID;
						agentSkill.SkillID = skillID;
						agentSkill.SkillValue = System.Int32.Parse(comboSkilled.SelectedValue.ToString());

						// add to list
						retValue.Add(agentSkill);
					}
				}

				// ok
				return retValue.ToArray();
			}
		}
		#endregion

		#region Search AD

		/// Called when search is close
		private void OnSearchWIndowClosed(EFS.Common.UI.Controls.ModalDialogHost host)
		{
			// search
			EFS.RC.CCAdmin.AD.Search opSearch = (EFS.RC.CCAdmin.AD.Search)host.HostedContent;

			// OK
			if (host.DialogClosedReason == EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok)
			{
				// logon name
				EFS.AD.User user = opSearch.SelectedUser;

				// set data
				textBoxLogonName.Text = user.LogonName;
				textBoxFirstName.Text = user.FirstName;
				textBoxLastName.Text = user.LastName;

				// create
				UtilitiesService.Agent_CreateAsync(officeEndpointID, user.ObjectGuid.ToString(), null);
			}
			else
			{
				this.host.Close();
			}
		}
		#endregion

		#region Utilities
		/// UpdateSkillsDataGrid
		private void UpdateSkillsDataGrid()
		{
			// cicle all
			foreach (EFS.RC.CC.Deployment.Entities.Skill skill in this.skillsCached)
			{
				// get controls
				System.Windows.Controls.CheckBox checkBox = dataGridSkills.Columns[0].GetCellContent(skill) as System.Windows.Controls.CheckBox;
				System.Windows.Controls.ComboBox comboSkilled = dataGridSkills.Columns[2].GetCellContent(skill) as System.Windows.Controls.ComboBox;

				// update
				if (checkBox.IsChecked.HasValue && checkBox.IsChecked.Value)
				{
					comboSkilled.IsEnabled = true;
				}
				else
				{
					comboSkilled.IsEnabled = false;
					comboSkilled.SelectedValue = null;
				}
			}
		}
		#endregion

		#region Service Events

		void UtilitiesService_AgentAD_GetByIDCompleted(object sender, WebProxy.AgentAD_GetByIDCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Failed to get Agent. ", e.Error);
			}

			try
			{
				// deserialize
				agentDetails = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.Deployment.Views.Operators.AgentADDetails>(e.Result.ToString());

				// check and load
				if (null != agentDetails)
				{
					// set data
					textBoxLogonName.Text = agentDetails.DomainLogonName;
					textBoxFirstName.Text = agentDetails.FirstName;
					textBoxLastName.Text = agentDetails.LastName;
				}
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to load data. " + ex.Message);
			}
		}

		/// UtilitiesService_Agent_CreateCompleted
		private void UtilitiesService_Agent_CreateCompleted(object sender, WebProxy.Agent_CreateCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Unable to Add Agent. ", e.Error);
			}
			else
			{
				try
				{
					// deserialize
					System.Int32? agentID = e.Result;

					// check and load
					if (null != agentID)
					{
						// load agent
						UtilitiesService.AgentAD_GetByIDAsync(agentID.Value);

						// load skills
						UtilitiesService.Skills_GetAllAsync();
					}
				}
				catch (System.Exception ex)
				{
					ShowErrorMessage("Failed to load data. " + ex.Message);
				}
			}
		}

		/// UtilitiesService_Agent_UpdateCompleted
		private void UtilitiesService_Agent_UpdateCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Unable to Upate Agent. ", e.Error);
			}
			else
			{
				host.Close(EFS.Common.UI.Controls.ModalDialogHost.ClosedReason.Ok);
			}
		}

		/// Skills_GetAllCompleted
		private void UtilitiesService_Skills_GetAllCompleted(object sender, WebProxy.Skills_GetAllCompletedEventArgs e)
		{
			//check if request was successful
			if (null != e.Error)
			{
				ShowErrorMessage("Failed to load Skills. ", e.Error);
			}
	
			try
			{
				// deserialize
				EFS.RC.CC.Deployment.Entities.Skill[] skills = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.Deployment.Entities.Skill[]>(e.Result.ToString());

				//bind/fill form
				dataGridSkills.ItemsSource = skills;

				// get all skills
				this.skillsCached = skills;

				// only if edit
				if (null != agentDetails)
				{
					UtilitiesService.AgentSkill_GetByAgentIDAsync(agentDetails.ID.Value);
				}
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to load data. " + ex.Message);
			}
		}

		/// AgentSkill_GetByAgentIDCompleted
		private void UtilitiesService_AgentSkill_GetByAgentIDCompleted(object sender, WebProxy.AgentSkill_GetByAgentIDCompletedEventArgs e)
		{
			try
			{
				//check if request was successful
				if (null != e.Error)
				{
					throw e.Error;
				}

				// deserialize
				EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill[] agentSkills = EFS.Common.Serialization.Functions.Deserialize<EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill[]>(e.Result.ToString());

				// update grid
				if (null != skillsCached)
				{
					// cicle all
					foreach (EFS.RC.CC.Deployment.Entities.Operators.Skills.Skill agentSkill in agentSkills)
					{
						// update grid
						foreach (EFS.RC.CC.Deployment.Entities.Skill skill in this.skillsCached)
						{
							// get checkbox
							System.Windows.Controls.CheckBox chk = dataGridSkills.Columns[0].GetCellContent(skill) as System.Windows.Controls.CheckBox;

							// get combo
							System.Windows.Controls.ComboBox comboSkilled = dataGridSkills.Columns[2].GetCellContent(skill) as System.Windows.Controls.ComboBox;

							// get ID
							System.Int32 skillID = System.Int32.Parse(chk.CommandParameter.ToString());

							// checked
                            if (skillID == agentSkill.SkillID)
                            {
                                //checkbox checked
                                chk.IsChecked = true;

                                //enable combobox
                                comboSkilled.IsEnabled = true;

                                //combobox value
                                comboSkilled.SelectedValue = agentSkill.SkillValue;
                            }
						}
					}

				}
			}
			catch (System.Exception ex)
			{
				ShowErrorMessage("Failed to load data. " + ex.Message);
			}
		}
		#endregion

		#region Events
		
		/// Load
		private void Edit_Loaded(object sender, System.Windows.RoutedEventArgs e)
		{
			// CREATE
			if (null == agentDetails)
			{
				EFS.Common.UI.Controls.ModalDialogHost wnd = new EFS.Common.UI.Controls.ModalDialogHost();
				wnd.HostedContent = new EFS.RC.CCAdmin.AD.Search();
				wnd.Show(OnSearchWIndowClosed);
			}
			// EDIT
			else
			{
				// set data
				textBoxLogonName.Text = agentDetails.DomainLogonName;
				textBoxFirstName.Text = agentDetails.FirstName;
				textBoxLastName.Text = agentDetails.LastName;

				// load skills
				UtilitiesService.Skills_GetAllAsync();
			}
		}

		/// <summary>
		/// Save agent
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/// <param name="dialogResult"></param>
		void SaveAgent(object sender, System.Windows.RoutedEventArgs e, System.Boolean dialogResult)
		{
			//ws call
			UtilitiesService.Agent_UpdateAsync(
					agentDetails.ID.Value, EFS.Common.Serialization.Functions.SerializeToString(SelectedSkills));
		}

		/// Loading row
		private void dataGridSkills_LoadingRow(object sender, System.Windows.Controls.DataGridRowEventArgs e)
		{
			// get combo
			System.Windows.Controls.ComboBox comboSkilled = dataGridSkills.Columns[2].GetCellContent(e.Row) as System.Windows.Controls.ComboBox;
            comboSkilled.ItemsSource = SkillValues;
		}
		
		/// checkbox was clicked
		private void checkboxSelected_Click(object sender, System.Windows.RoutedEventArgs e)
        {
			UpdateSkillsDataGrid();
        }
		#endregion
	}

}